package database

import (
	"admin-system/config"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"os"
	"time"
)

func NewDatabase(cfg *config.Config) (*gorm.DB, error) {
	// 设置日志等级
	var logLevel logger.LogLevel
	switch cfg.Database.LogLevel {
	case "silent":
		logLevel = logger.Silent
	case "error":
		logLevel = logger.Error
	case "warn":
		logLevel = logger.Warn
	case "info":
		logLevel = logger.Info
	default:
		logLevel = logger.Warn
	}
	// 配置gorm logger
	newlogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags),
		logger.Config{
			SlowThreshold: time.Second,
			LogLevel:      logLevel,
			Colorful:      false,
		})
	// 初始化数据库连接
	dsn := cfg.GetDatabaseDSN()
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: newlogger,
	})
	if err != nil {
		return nil, err
	}
	// 配置连接池
	sqlDB, err := db.DB()
	if err != nil {
		return nil, err
	}
	sqlDB.SetMaxIdleConns(cfg.Database.MaxIdleConnections)
	sqlDB.SetMaxOpenConns(cfg.Database.MaxOpenConnections)
	sqlDB.SetConnMaxLifetime(time.Hour)

	return db, nil
}
